<template>
  <div class="ticket">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="box-card">
          <div class="boxcard-head">
            <el-form :model="queryParam" :inline="true" class="demo-form-inline" ref="queryParam">
              <el-form-item label="时间范围:" prop="timespan">
                <el-date-picker
                  v-model="queryParam.timespan"
                  type="daterange"
                  unlink-panels
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="优惠金额范围" prop="subtractAmoutMin">
                <el-input
                  v-model="queryParam.subtractAmoutMin"
                  autocomplete="off"
                  clearable
                  type="number"
                  min="0"
                ></el-input>
              </el-form-item>
              <el-form-item label="~" prop="subtractAmoutMax">
                <el-input
                  v-model="queryParam.subtractAmoutMax"
                  autocomplete="off"
                  clearable
                  type="number"
                  min="0"
                ></el-input>
              </el-form-item>
              <el-form-item label="类型" prop="type" clearable>
                <el-select v-model="queryParam.type" placeholder="请选择">
                  <el-option
                    v-for="item in typeOptions"
                    :key="item.key"
                    :label="item.label"
                    :value="item.key"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="状态" prop="status" clearable>
                <el-select v-model="queryParam.status" placeholder="请选择">
                  <el-option :key="1" label="草稿" :value="1"></el-option>
                  <el-option :key="2" label="已发布" :value="2"></el-option>
                  <el-option :key="3" label="已过期" :value="3"></el-option>
                  <el-option :key="4" label="已删除" :value="4"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="searchTicket">查询</el-button>
                <el-button @click="resetQueryParamForm('queryParam')">重置</el-button>
                <el-button type="primary" icon="el-icon-plus" @click="addTicket">添加</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="boxcard-body">
            <el-table
              :data="list"
              style="width: 100%;"
              row-key="id"
              :header-cell-style="{ 'background-color': '#EEEEEE' }"
            >
              <el-table-column prop="name" label="名字"></el-table-column>
              <el-table-column prop="description" label="备注"></el-table-column>
              <el-table-column prop="beginDate" label="开始时间"></el-table-column>
              <el-table-column prop="endDate" label="结束时间"></el-table-column>
              <el-table-column prop="status" label="状态">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.status == 1">草稿</el-tag>
                  <el-tag v-if="scope.row.status == 2">已发布</el-tag>
                  <el-tag v-if="scope.row.status == 3">已过期</el-tag>
                  <el-tag v-if="scope.row.status == 4">已删除</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="overAmount" label="订单额超过"></el-table-column>
              <el-table-column prop="subtractAmout" label="优惠金额"></el-table-column>
              <el-table-column prop="type" label="类型">
                <template slot-scope="scope">{{getlabel(scope.row.type,typeOptions)}}</template>
              </el-table-column>
              <el-table-column prop="subType" label="子类型">
                <template slot-scope="scope">{{getlabel(scope.row.subType,subTypes)}}</template>
              </el-table-column>
              <el-table-column prop="publishUserName" label="发布人"></el-table-column>
              <el-table-column prop="publishDate" label="发布时间"></el-table-column>
              <el-table-column label="操作" width="220">
                <template slot-scope="scope">
                  <el-button type="text" size="small" @click="updateTicket(scope.row)">修改</el-button>
                  <el-button
                    v-if="scope.row.status!=4"
                    type="text"
                    size="small"
                    @click="deleteTicket(scope.row)"
                  >删除</el-button>
                  <el-button
                    v-if="scope.row.status==1 || scope.row.status==4 || scope.row.status==3"
                    @click="publish(scope.row)"
                    type="text"
                    size="small"
                  >发布</el-button>
                  <el-button
                    v-if="scope.row.type===5&&scope.row.status==2"
                    @click="pauseSend(scope.row)"
                    type="text"
                    size="small"
                  >{{scope.row.isPauseSend===true?'开始发放':'暂停发放'}}</el-button>
                  <el-button type="text" size="small" @click="ticketUseDetail(scope.row)">优惠卷统计</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="pagination">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page.currentPage"
              :page-sizes="page.pageSizes"
              :page-size="page.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="page.total"
            ></el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <edit ref="ticketEdit" v-bind:visible.sync="ticketEditDialog" @success="getlist"></edit>
    <ticketUseDetail v-bind:visible.sync="ticketUseDetailVisable" ref="ticketUseDetail"></ticketUseDetail>
  </div>
</template>

<script>
import { get, postJson, postXform } from "@/utils/request.js";
import edit from "./ticketEdit";
import ticketUseDetail from "./ticketUseDetail";
export default {
  components: { edit, ticketUseDetail },
  created() {
    this.getlist();
  },
  watch: {},
  data() {
    return {
      queryParam: {
        timespan: null,
        subtractAmoutMin: null,
        subtractAmoutMax: null,
        type: null,
        status: null
      },
      list: [],
      rules: {},
      ticketEditDialog: false,
      dialog: { title: "添加优惠券", visible: false },
      page: { currentPage: 1, pageSize: 10, pageSizes: [10, 20, 50], total: 0 },
      ticket: {
        id: "",
        beginDate: "",
        endDate: "",
        status: "",
        overAmount: "",
        subtractAmout: ""
      },
      typeOptions: [
        { key: 0, label: "所有人" },
        { key: 1, label: "按客户类型" },
        { key: 2, label: "按客户来源" },
        { key: 3, label: "选择客户" },
        { key: 4, label: "客户会员等级" },
        { key: 5, label: "注册送优惠卷" }
      ],
      subTypes: [
        { key: 1, label: "客户" },
        { key: 2, label: "医生" },
        { key: 3, label: "员工" },
        { key: 4, label: "分销商" },
        { key: 5, label: "筛查活动" },
        { key: 6, label: "门店" },
        { key: 7, label: "医生" },
        { key: 8, label: "分销商" },
        { key: 9, label: "客户" },
        { key: 10, label: "其他" }
      ],
      ticketUseDetailVisable: false
    };
  },
  methods: {
    getlabel(key, arr) {
      for (var i = 0; i < arr.length; i++) {
        if (arr[i].key == key) {
          return arr[i].label;
        }
      }
      return "";
    },
    async getlist() {
      let startDate, endDate;
      if (this.queryParam.timespan && this.queryParam.timespan.length > 0) {
        startDate = this.queryParam.timespan[0];
        endDate = this.queryParam.timespan[1];
      }
      await get("/preferentialTicket/pagePreferentialTicket", {
        pageNum: this.page.currentPage,
        pageSize: this.page.pageSize,
        startDate: startDate,
        endDate: endDate,
        subtractAmoutMin: this.queryParam.subtractAmoutMin,
        subtractAmoutMax: this.queryParam.subtractAmoutMax,
        type: this.queryParam.type,
        status: this.queryParam.status
      }).then(res => {
        this.list = res.data.data.list;
        this.page.total = Number.parseInt(res.data.data.total);
        this.page.currentPage = res.data.data.pageNum;
      });
    },
    searchTicket() {
      this.getlist();
    },
    addTicket() {
      this.ticketEditDialog = true;
      this.$refs.ticketEdit.initEdit();
      // this.resetForm();
      // this.dialog.visible = true;
      // this.$nextTick(() => {
      //     this.$refs.imgFileRef.init();
      // });
    },
    updateTicket(ticket) {
      // this.dialog.visible = true;
      // this.dialog.title = '修改优惠券';
      // this.ticket = {...ticket};
      this.ticketEditDialog = true;
      this.$refs.ticketEdit.initEdit(ticket);
      // this.ticket.imageUrl = [ { name: ticket.imageUrl, url: ticket.imageUrl } ];
      // this.$nextTick(() => {
      //   this.$refs.imgFileRef.init();
      // });
    },
    deleteTicket(ticket) {
      this.$confirm("是否删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          postXform("/preferentialTicket/deletePreferentialTicket", {
            id: ticket.id
          }).then(res => {
            this.$message({ message: "删除成功", type: "success" });
            this.getlist();
          });
        })
        .catch(() => {});
    },
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.getlist();
    },
    handleCurrentChange(val) {
      this.page.currentPage = val;
      this.getlist();
    },
    submitForm() {
      this.$refs.ticket.validate(valid => {
        let param = {
          id: this.ticket.id,
          endDate: this.ticket.endDate,
          overAmount: this.ticket.overAmount,
          subtractAmout: this.ticket.subtractAmout
        };
        // if (this.ticket.imageUrl.length > 0) {
        //   param.imageUrl = this.ticket.imageUrl[0].url;
        // } else {
        //   param.imageUrl = null;
        // }
        if (valid) {
          if (this.ticket.id === "") {
            postXform("/preferentialTicket/addPreferentialTicket", param).then(
              res => {
                this.dialog.visible = false;
                this.$message({ message: "添加成功", type: "success" });
                this.getlist();
              }
            );
          } else {
            postXform(
              "/preferentialTicket/updatePreferentialTicket",
              param
            ).then(res => {
              this.dialog.visible = false;
              this.$message({ message: "修改成功", type: "success" });
              this.getlist();
            });
          }
        }
      });
    },
    resetForm() {
      this.ticket = {
        id: "",
        imageUrl: [],
        beginDate: "",
        endDate: "",
        status: "",
        overAmount: "",
        subtractAmout: ""
      };
    },
    publish(e) {
      this.$confirm("发布后，除优惠卷时间外其他属性不可修改！", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          postXform("/preferentialTicket/publish", { id: e.id }).then(res => {
            this.$message({ message: "操作成功", type: "success" });
            this.getlist();
          });
        })
        .catch(() => {});
    },
    resetQueryParamForm(formName) {
      this.$refs[formName].resetFields();
      if (formName == "queryParam") {
        this.getlist();
      }
    },
    ticketUseDetail(row) {
      this.$refs.ticketUseDetail.initComponent(row.id);
      this.ticketUseDetailVisable = true;
    },
    pauseSend(row) {
      this.$https
        .postXform("/preferentialTicket/pauseSend", {
          id: row.id,
          isPauseSend: !row.isPauseSend
        })
        .then(res => {
          this.$message({ message: "操作成功", type: "success" });
          row.isPauseSend = !row.isPauseSend;
        });
    }
  }
};
</script>

<style lang="less">
.formItem {
  display: flex;
  flex-direction: row;
  position: relative;
}
</style>
